package com.ssl.replation.service.impl;

import com.ssl.replation.dao.UserMapper;
import com.ssl.replation.model.User;
import com.ssl.replation.model.UserExample;
import com.ssl.replation.service.UserService;
import org.apache.shardingsphere.infra.hint.HintManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 描述：
 *
 * @author ssl
 * @create 2021/7/23 0023.
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User create(String name) {
        User user = new User();
        user.setName(name);
        // 写操作会自动选择master库
        userMapper.insert(user);
        System.out.println(user.getId());
        // 查询 会自动选择slave库
        System.out.println("使用读库查询"+userMapper.selectByPrimaryKey(user.getId()));
        // 强制使用master查询
        HintManager.getInstance().setWriteRouteOnly();
        System.out.println("强制使用写库查询："+userMapper.selectByPrimaryKey(user.getId()));
        return user;
    }

    @Override
    public User get(String name) {
        UserExample example = new UserExample();
        example.createCriteria().andNameEqualTo(name);
        List<User> list = userMapper.selectByExample(example);
        if (null == list || list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }
}
